//
//  ImageWorkedViewController.m
//  Scanner
//
//  Created by TGBUS on 12-7-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ImageWorkedViewController.h"
#import "ImageUtlity.h"
#import "UIImage+Extension.h"

@interface ImageWorkedViewController () {
@private
}

-(void)undoAction:(id)sender;                       //Undo操作
-(void)clearAction:(id)sender;                      //Clear操作
-(void)rgbViewAction:(id)sender;                    //显示调节RGB的滑竿操作
-(void)enableControllers:(NSNumber *)flag;          //是否禁用控件
-(void)useAction:(id)sender;                        //结束处理图片操作
-(void)sliderChanged:(id)sender;                    //滑竿滑动停止后的处理事件

@end

@implementation ImageWorkedViewController

@synthesize context,metrixFilter,colorFilter,processImage,colorFilter2;
@synthesize imageProcessDelegate;
@synthesize sourceImagePath;
@synthesize sliderView;
@synthesize imgView;
@synthesize bottomToolBar;
@synthesize segmentController;
@synthesize redSlider,greenSlider,blueSlider,brightSlider,contrastSlider;
@synthesize lblRedToCyan,lblBlueToYellow,lblGreenToMagenta,lblBright,lblContrast;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)refreshImageView
{
    [imgView setImage:[UIImage imageWithContentsOfFile:kPhotoedImagePath]];
    self.processImage=[CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:kPhotoedImagePath]];
}

-(void)undoAction:(id)sender
{
    CATransition *transition=[CATransition animation];
    transition.duration=1.0;
    transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type=@"oglFlip";
    transition.subtype=kCATransitionFromBottom;
    [imgView.layer addAnimation:transition forKey:nil];
    if(isClear)
    {
        [self clearAction:nil];
    }
    else
    {
        [redSlider setValue:0.4 animated:YES];
        [greenSlider setValue:0.6 animated:YES];
        [blueSlider setValue:0.7 animated:YES];
        [brightSlider setValue:0 animated:YES];
        [contrastSlider setValue:1 animated:YES];
        [self sliderChanged:nil];
    }
}

-(void)clearAction:(id)sender
{
    isClear=YES;
    //动画形式将滑竿都恢复至中值
    [redSlider setValue:0 animated:YES];
    [greenSlider setValue:0 animated:YES];
    [blueSlider setValue:0 animated:YES];
    [brightSlider setValue:0 animated:YES];
    [contrastSlider setValue:1 animated:YES];
    
    [self refreshImageView];
}

-(void)enableControllers:(NSNumber *)flag
{
    for(int i=0;i<[bottomToolBar.items count];i++)
    {
        if(i!=1)
        {
            UIControl *controller=[bottomToolBar.items objectAtIndex:i];
            [controller setEnabled:[flag boolValue]];
        }
    }
}

-(void)rgbViewAction:(id)sender
{   
    [self enableControllers:[NSNumber numberWithBool:NO]];
    CATransition *transition=[CATransition animation];
    transition.duration=1.0;
    transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type=@"oglFlip";
    if(isBackView)
    {
        transition.subtype=kCATransitionFromRight;
        [redSlider setHidden:NO];
        [greenSlider setHidden:NO];
        [blueSlider setHidden:NO];
        [lblRedToCyan setHidden:NO];
        [lblGreenToMagenta setHidden:NO];
        [lblBlueToYellow setHidden:NO];
        [lblBright setHidden:YES];
        [lblContrast setHidden:YES];
        [brightSlider setHidden:YES];
        [contrastSlider setHidden:YES];
    }
    else
    {
        transition.subtype=kCATransitionFromLeft;
        [redSlider setHidden:YES];
        [greenSlider setHidden:YES];
        [blueSlider setHidden:YES];
        [lblRedToCyan setHidden:YES];
        [lblGreenToMagenta setHidden:YES];
        [lblBlueToYellow setHidden:YES];
        [lblBright setHidden:NO];
        [lblContrast setHidden:NO];
        [brightSlider setHidden:NO];
        [contrastSlider setHidden:NO];
    }
    
    [sliderView.layer addAnimation:transition forKey:nil];

    isBackView=!isBackView;
    [self performSelector:@selector(enableControllers:) withObject:[NSNumber numberWithBool:YES] afterDelay:1.0];
}

-(void)useAction:(id)sender
{
    if([imageProcessDelegate respondsToSelector:@selector(ImageProcessedFinished:)])
    {
        [imageProcessDelegate ImageProcessedFinished:imgView.image];
    }
    [self dismissModalViewControllerAnimated:YES];
}

-(void)sliderChanged:(id)sender
{
    if(processImage==nil)
    {
        NSLog(@"要处理的图片是nil");
        return;
    }
    //RGB像素处理
    [metrixFilter setValue:processImage forKey:kCIInputImageKey];
    [metrixFilter setValue:[CIVector vectorWithX:(redSlider.maximumValue-redSlider.value) Y:0 Z:0] forKey:@"inputRVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:(greenSlider.maximumValue-greenSlider.value) Z:0] forKey:@"inputGVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:0 Z:(blueSlider.maximumValue-blueSlider.value)] forKey:@"inputBVector"];
    
    CIImage *outMetrixImage=[metrixFilter outputImage];
    
    //颜色--亮度和对比度处理
    [colorFilter setValue:outMetrixImage forKey:kCIInputImageKey];
    [colorFilter setValue:[NSNumber numberWithFloat:contrastSlider.value] forKey:@"inputContrast"];
    [colorFilter setValue:[NSNumber numberWithFloat:brightSlider.value] forKey:@"inputBrightness"];
//    [colorFilter setValue:[NSNumber numberWithFloat:1.0] forKey:@"inputSaturation"];
    CIImage *outImage=[colorFilter outputImage];
    
    CGImageRef cgImg=[context createCGImage:outImage fromRect:outImage.extent];
    UIImage *newImg=[UIImage imageWithCGImage:cgImg];
    [imgView setImage:newImg];
    CGImageRelease(cgImg);
}

#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];

    [self.view setBackgroundColor:[UIColor blackColor]];
    
    //显示的照片
    imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 440)];
    UIImage *originImage=[UIImage imageWithContentsOfFile:kPhotoedImagePath];
    UIImage *rotatedImg=[originImage fixOrientation];

    if(rotatedImg!=nil)
    {
        [imgView setImage:rotatedImg];
    }
    else
    {
        [imgView setImage:originImage];
    }
    [self.view addSubview:imgView];
    
    //----------------------------标签和滑竿-------------------------
    CGFloat orginX=10;
    CGFloat height=20;
    CGFloat sliderWidth=280;

    //承载滑竿的视图
    sliderView=[[UIView alloc] initWithFrame:CGRectMake(10, 280, 300, height*6+20)];
    [sliderView setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.7]];
    sliderView.layer.cornerRadius=8;
    [self.view addSubview:sliderView];
    
    
    
    lblRedToCyan=[[UILabel alloc] initWithFrame:CGRectMake(orginX, 5, sliderWidth, height)];
    [lblRedToCyan setTextColor:[UIColor whiteColor]];
    [lblRedToCyan setTextAlignment:UITextAlignmentCenter];
    [lblRedToCyan setBackgroundColor:[UIColor clearColor]];
    [lblRedToCyan setText:@"Red                                        Cyan"];
    [sliderView addSubview:lblRedToCyan];
    
    redSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX, lblRedToCyan.frame.origin.y+height, sliderWidth, height)];
    [redSlider setTag:500];
    [redSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [redSlider setMaximumValue:1];
    [redSlider setMinimumValue:-1];
    [sliderView addSubview:redSlider];
    
    lblGreenToMagenta=[[UILabel alloc] initWithFrame:CGRectMake(orginX, redSlider.frame.origin.y+height, sliderWidth, height)];
    [lblGreenToMagenta setTextColor:[UIColor whiteColor]];
    [lblGreenToMagenta setTextAlignment:UITextAlignmentCenter];
    [lblGreenToMagenta setBackgroundColor:[UIColor clearColor]];
    [lblGreenToMagenta setText:@"Green                                Magenta"];
    [sliderView addSubview:lblGreenToMagenta];
    
    greenSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblGreenToMagenta.frame.origin.y+height, sliderWidth, height)];
    [greenSlider setTag:501];
    [greenSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [greenSlider setMaximumValue:1];
    [greenSlider setMinimumValue:-1];
    [sliderView addSubview:greenSlider];
    
    lblBlueToYellow=[[UILabel alloc] initWithFrame:CGRectMake(orginX, greenSlider.frame.origin.y+height, sliderWidth, height)];
    [lblBlueToYellow setTextColor:[UIColor whiteColor]];
    [lblBlueToYellow setTextAlignment:UITextAlignmentCenter];
    [lblBlueToYellow setBackgroundColor:[UIColor clearColor]];
    [lblBlueToYellow setText:@"Blue                                     Yellow"];
    [sliderView addSubview:lblBlueToYellow];
    
    blueSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblBlueToYellow.frame.origin.y+height, sliderWidth, height)];
    [blueSlider setTag:502];
    [blueSlider setMaximumValue:1];
    [blueSlider setMinimumValue:-1];
    [blueSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:blueSlider];
  
    //调节亮度和对比度的
    CGFloat height2=30;
    lblBright=[[UILabel alloc] initWithFrame:CGRectMake(orginX,5, sliderWidth, height2)];
    [lblBright setTextColor:[UIColor whiteColor]];
    [lblBright setTextAlignment:UITextAlignmentCenter];
    [lblBright setBackgroundColor:[UIColor clearColor]];
    [lblBright setFont:[UIFont fontWithName:@"Helvetia" size:16]];
    [lblBright setText:@"Brightness"];
    [lblBright setHidden:YES];
    [sliderView addSubview:lblBright];
    
    brightSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblBright.frame.origin.y+height2, sliderWidth, height)];
    [brightSlider setTag:503];
    [brightSlider setMaximumValue:0.5];
    [brightSlider setMinimumValue:-0.5];
    [brightSlider setHidden:YES];
    [brightSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:brightSlider];

    lblContrast=[[UILabel alloc] initWithFrame:CGRectMake(orginX,brightSlider.frame.origin.y+height2, sliderWidth, height2)];
    [lblContrast setTextColor:[UIColor whiteColor]];
    [lblContrast setTextAlignment:UITextAlignmentCenter];
    [lblContrast setBackgroundColor:[UIColor clearColor]];
    [lblContrast setFont:[UIFont fontWithName:@"Helvetia" size:16]];
    [lblContrast setText:@"Contrast"];
    [lblContrast setHidden:YES];
    [sliderView addSubview:lblContrast];
    
    contrastSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblContrast.frame.origin.y+height2, sliderWidth, height)];
    [contrastSlider setTag:504];
    [contrastSlider setHidden:YES];
    [contrastSlider setMaximumValue:4];
    [contrastSlider setMinimumValue:0];
    [contrastSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:contrastSlider];

    [self undoAction:nil];
    //---------------------------------------------------------------
    
    //底部的操作栏
    bottomToolBar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 440, 320, 44)];
//    [bottomToolBar setTintColor:[UIColor colorWithRed:214/255.0 green:214/255.0 blue:214/255.0 alpha:1.0]];
    [bottomToolBar setBarStyle:UIBarStyleBlackOpaque];
    
    //Undo Bar
    UILabel *lblUndo=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [lblUndo setText:@"Undo"];
    [lblUndo setBackgroundColor:[UIColor clearColor]];
    [lblUndo setTextColor:[UIColor blackColor]];
    UIBarButtonItem *undoBar=[[[UIBarButtonItem alloc] initWithTitle:@"Undo" style:UIBarButtonItemStyleBordered target:self action:@selector(undoAction:)] autorelease];
    
    //Clear Bar
    UIBarButtonItem *clearBar=[[[UIBarButtonItem alloc] initWithTitle:@"Clear" style:UIBarButtonItemStyleBordered target:self action:@selector(clearAction:)] autorelease];
    
    //空格1
    UIBarButtonItem *spaceBarOne=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil] autorelease];
    [spaceBarOne setWidth:10];
    
    //调节rgb和亮度的分段bar
    segmentController=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"",@"", nil]];
    [segmentController setSegmentedControlStyle:UISegmentedControlStyleBar];
    [segmentController setSelectedSegmentIndex:0];
    [segmentController addTarget:self action:@selector(rgbViewAction:) forControlEvents:UIControlEventValueChanged];
    [segmentController setFrame:CGRectMake(0, 4, 100, 30)];
    [segmentController setImage:[UIImage imageNamed:@"rgbIcon.png"] forSegmentAtIndex:0];
    [segmentController setImage:[UIImage imageNamed:@"bandCicon.png"] forSegmentAtIndex:1];
    
    UIBarButtonItem *segmentBar=[[[UIBarButtonItem alloc] initWithCustomView:segmentController]autorelease];
    
    //空格2
    UIBarButtonItem *spaceBarTwo=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil] autorelease];
    [spaceBarTwo setWidth:10];
    
    //Use Bar
    UIBarButtonItem *useBar=[[[UIBarButtonItem alloc] initWithTitle:@"Use" style:UIBarButtonItemStyleBordered target:self action:@selector(useAction:)] autorelease];

    [bottomToolBar setItems:[NSArray arrayWithObjects:undoBar,clearBar ,spaceBarOne,segmentBar,spaceBarTwo,useBar,nil]];
    [self.view addSubview:bottomToolBar];
    [bottomToolBar release];

    
    
    NSURL *url=[NSURL fileURLWithPath:kPhotoedImagePath];
    self.processImage=[CIImage imageWithContentsOfURL:url];
    
    // 创建基于GPU的CIContext对象
    self.context = [CIContext contextWithOptions: nil];
    
    // 创建基于CPU的CIContext对象
    //context = [CIContext contextWithOptions: [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:kCIContextUseSoftwareRenderer]];
    
    // 创建过滤器
    self.colorFilter = [CIFilter filterWithName:@"CIColorControls"];
    self.colorFilter2 = [CIFilter filterWithName:@"CIColorControls"];
    self.metrixFilter = [CIFilter filterWithName:@"CIColorMatrix"];
    [self sliderChanged:nil];
}

//用于打印所有过滤器的键值
//- (void)logAllFilters {
//    NSArray *properties = [CIFilter filterNamesInCategory:
//                           kCICategoryBuiltIn];
//    NSLog(@"FilterName:\n%@", properties);
//    for (NSString *filterName in properties) {
//        CIFilter *fltr = [CIFilter filterWithName:filterName];
//        NSLog(@"%@:\n%@", filterName, [fltr attributes]);
//    }
//}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"Edit Mode:Your image has been color optimized!Would you like to edit futher?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
    [alert show];
    [alert release];
}

-(void)releaseData
{
    self.sliderView=nil;
    self.greenSlider=nil;
    self.blueSlider=nil;
    self.redSlider=nil;
    self.imgView=nil;
    self.lblRedToCyan=nil;
    self.lblGreenToMagenta=nil;
    self.segmentController=nil;
    self.lblBlueToYellow=nil;
    self.brightSlider=nil;
    self.contrastSlider=nil;
    self.lblBright=nil;
    self.lblContrast=nil;
    self.sourceImagePath=nil;
    self.imageProcessDelegate=nil;
    self.colorFilter=nil;
    self.metrixFilter=nil;
    self.context=nil;
    self.processImage=nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self releaseData];
}

-(void)dealloc
{
    self.bottomToolBar=nil;
    [self releaseData];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma UIAlert委托回调

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0://Yes
            break;
        case 1://No
          if([imageProcessDelegate respondsToSelector:@selector(ImageProcessedFinished:)])
            {
                [imageProcessDelegate ImageProcessedFinished:imgView.image];
            }
            [self dismissModalViewControllerAnimated:YES];
            break;
        default:
            break;
    }
}

@end
